package likouJava;

public class 环形链表2 {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next ==null){
            return null;
        }

        //创建快慢指针
        ListNode slow = head;
        ListNode fast = head;


        //如果有环，一定会相等
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast){
                break;
            }
        }
        if (fast == null || fast.next == null){
            return null;
        }
        slow = head;
        while (slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

}
